<template>
  <!--过程反馈（工序）详情-->
  <el-container style="display: block">
    <el-collapse v-if="!props.hiddenForm" ref="collapse" style="margin-bottom: 10px"
                 @change="collapseChange" v-model="activeNames">
      <el-collapse-item name="1" title="规程详情">
        <div style="display: flex;">
          <el-descriptions :column="formColumn" style="width: calc(100% - 420px)">
            <el-descriptions-item label="计划编号:">{{parentRow.sourceCode}}</el-descriptions-item>
            <el-descriptions-item label="批次号:">{{parentRow.batchNum}}</el-descriptions-item>
            <el-descriptions-item label="项目号:">{{parentRow.workOrderCode}}</el-descriptions-item>
            <el-descriptions-item label="产品主管:">{{parentRow.assignerName}}</el-descriptions-item>
            <el-descriptions-item label="产品型号:">{{parentRow.modelName}}</el-descriptions-item>
            <el-descriptions-item label="产品编号:">{{parentRow.pdmProductCode}}</el-descriptions-item>
            <el-descriptions-item label="产品名称:">{{parentRow.pdmProductName}}</el-descriptions-item>
            <el-descriptions-item label="规程编号:">{{parentRow.code}}</el-descriptions-item>
            <el-descriptions-item label="规程名称:">{{parentRow.name}}</el-descriptions-item>
            <el-descriptions-item label="规程版本:">{{parentRow.specificationRev}}</el-descriptions-item>
            <el-descriptions-item label="计划结束时间:">{{formatDate(parentRow.needEndDate, 'yyyy-MM-dd')}}</el-descriptions-item>
            <el-descriptions-item label="工步流转卡号:">{{parentRow.processCardNo}}</el-descriptions-item>
          </el-descriptions>
          <div style="width: 410px;margin-left: 10px">
            <div style="border: 1px solid #66b1ff;border-radius: 5px;padding: 5px 0">
              <div>
                <el-tooltip content="设备工具" effect="dark" placement="top">
                  <i class="iconfont icon-shebei"></i>
                </el-tooltip>
                设备工具&nbsp;&nbsp;&nbsp;&nbsp;
                <el-tooltip content="安装记录" effect="dark" placement="top">
                  <i class="iconfont icon-anzhuangjilu"></i>
                </el-tooltip>
                安装记录&nbsp;&nbsp;&nbsp;&nbsp;
                <el-tooltip content="记录取号" effect="dark" placement="top">
                  <i class="iconfont icon-quhaojilu"></i>
                </el-tooltip>
                记录取号&nbsp;&nbsp;&nbsp;&nbsp;
                <el-tooltip content="查杀毒记录" effect="dark" placement="top">
                  <i class="iconfont icon-icon-quanbuchuzhi"></i>
                </el-tooltip>
                查杀毒记录&nbsp;&nbsp;&nbsp;&nbsp;
              </div>
              <div>
                <el-tooltip content="问题反馈单" effect="dark" placement="top">
                  <i class="iconfont icon-guzhangjilu"></i>
                </el-tooltip>
                问题反馈单&nbsp;&nbsp;&nbsp;&nbsp;
                <el-tooltip content="工艺有文件" effect="dark" placement="top">
                  <el-icon class="iconfont" style="color: var(--el-collapse-content-text-color);top:2px"><Document /></el-icon>
                </el-tooltip>
                工艺文件&nbsp;&nbsp;&nbsp;&nbsp;
                <el-tooltip content="生产过程信息记录表" effect="dark" placement="top">
                  <i class="iconfont icon-shengchanguochengjilu"></i>
                </el-tooltip>
                生产过程信息记录表&nbsp;&nbsp;&nbsp;&nbsp;
              </div>
              <div>
                <el-tooltip content="不合格审理单" effect="dark" placement="top">
                  <i class="iconfont icon-terms"></i>
                </el-tooltip>
                不合格审理单&nbsp;&nbsp;&nbsp;&nbsp;
                <el-tooltip content="关键工序质量控制表" effect="dark" placement="top">
                  <i class="iconfont icon-guanjiangongxu"></i>
                </el-tooltip>
                关键工序质量控制表&nbsp;&nbsp;&nbsp;&nbsp;
                <el-tooltip content="提交用户申请单" effect="dark" placement="top">
                  <i class="iconfont icon-ic_fluent_checkbox_person_24_filled"></i>
                </el-tooltip>
                提交用户申请单
              </div>
            </div>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <basic-crud  ref="crudRef" :option="option" apiGetListUrl="/mes/processTaskController/listTaskHasBill"
                 apiGetListMethod="post" selectType="multiple" :autoLoad="crudAutoLoad"
                 :fastSearch="{name:'工步号、工步名称',fastColumn:'code,name'}"
                 :defaultListParams="orderParams" :apiListParams="listParams">
      <template #status="{ row }">
        <el-tag v-if="row.status === 'Suspended'" type="danger">{{row.statusShow}}</el-tag>
        <el-tag v-else-if="row.status === 'Obsoleted'" type="info">{{row.statusShow}}</el-tag>
        <el-tag v-else-if="row.status === 'ExecuteFinish' && mode == 'checker'" type="warning">待检验</el-tag>
        <el-tag v-else-if="row.status === 'ExecuteFinish' || row.status === 'Finish'"
                type="success">
          {{ row.statusShow }}
        </el-tag>
        <el-tag v-else>{{ row.statusShow }}</el-tag>
      </template>
      <template #code="{ row }">
        <el-button type="text" @click="handleOpenForm(billKey.code, row)">{{ row.code }}</el-button>
      </template>
      <template #fixedArmyFlag="{ row }">
        <el-tag v-if="row.fixedArmyFlag === 'true'" type="danger">是</el-tag>
      </template>
      <template #billCode="{ row }">
        <div style="display: flex">
          <div class="item" title="有设备需要选择">
            <i v-if="inArray(row.billCode, billKey.processDeCode)" class="iconfont icon-shebei icon-margin"> </i>
          </div>
          <div class="item" title="有待装件需要处理">
            <i v-if="inArray(row.billCode, billKey.installItem)" class="iconfont icon-anzhuangjilu icon-margin"></i>
          </div>
          <div class="item" title="需要取号">
            <i v-if="inArray(row.billCode, billKey.takeNumber)" class="iconfont icon-quhaojilu icon-margin"></i>
          </div>
          <div class="item" title="需要添加查杀毒记录">
            <i v-if="inArray(row.billCode, billKey.antivirusRecords)"
               class="iconfont icon-icon-quanbuchuzhi icon-margin"></i>
          </div>
          <div class="item" title="有问题反馈单需要填写">
            <i v-if="inArray(row.billCode, billKey.feedback)" class="iconfont icon-guzhangjilu icon-margin"></i>
          </div>
          <div class="item" title="有不合格品单需要填写">
            <i v-if="inArray(row.billCode, billKey.qualified)" class="iconfont icon-terms icon-margin"></i>
          </div>
          <div class="item" title="生产过程记录表需要填写">
            <i v-if="inArray(row.billCode, billKey.produceRecord)"
               class="iconfont icon-shengchanguochengjilu icon-margin"></i>
          </div>
          <div class="item" title="关键工序质量表">
            <i v-if="inArray(row.billCode, billKey.processKeyRecord)"
               class="iconfont icon-guanjiangongxu icon-margin"></i>
          </div>
          <div class="item" title="提交用户申请单">
            <i v-if="inArray(row.billCode, billKey.submitCode)"
               class="iconfont icon-ic_fluent_checkbox_person_24_filled icon-margin"></i>
          </div>
          <div class="item" title="有工艺附件">
            <el-icon v-if="inArray(row.billCode, billKey.code)" class="icon-margin"
                     style="color: #606266;fill:#606266;top:3px;font-size: 16px"><Document /></el-icon>
          </div>
        </div>
      </template>
      <template #menu="{ row }">
        <div v-if="isStep(row)">
          <el-badge :hidden="wrapperToolTip(row,billKey.processDeCode)" :value="getToolTipValue(row,billKey.processDeCode)"
                    class="techne-badge item">
            <el-tooltip class="item" content="设备工具" effect="dark" placement="top">
              <i class="iconfont icon-shebei" @click="handleOpenForm(billKey.processDeCode, row)"></i>
            </el-tooltip>
          </el-badge>
          <el-badge :hidden="wrapperToolTip(row,billKey.installItem)" :value="getToolTipValue(row,billKey.installItem)"
                    class="techne-badge item">
            <el-tooltip class="item" content="安装记录" effect="dark" placement="top">
              <i class="iconfont icon-anzhuangjilu" @click="handleOpenForm(billKey.installItem,row)"></i>
            </el-tooltip>
          </el-badge>
          <el-badge :hidden="wrapperToolTip(row,billKey.takeNumber)" :value="getToolTipValue(row,billKey.takeNumber)"
                    class="techne-badge item">
            <el-tooltip class="item" content="记录取号" effect="dark" placement="top">
              <i class="iconfont icon-quhaojilu" @click="handleOpenForm(billKey.takeNumber, row)"></i>
            </el-tooltip>
          </el-badge>
          <el-badge :hidden="wrapperToolTip(row,billKey.antivirusRecords)" :value="getToolTipValue(row,billKey.antivirusRecords)"
                    class="techne-badge item">
            <el-tooltip class="item" content="查杀毒记录" effect="dark" placement="top">
              <i class="iconfont icon-icon-quanbuchuzhi" @click="handleOpenForm(billKey.antivirusRecords, row)"></i>
            </el-tooltip>
          </el-badge>
          <el-badge :hidden="wrapperToolTip(row,billKey.feedback)" :value="getToolTipValue(row,billKey.feedback)"
                    class="techne-badge item">
            <el-tooltip class="item" content="问题反馈单" effect="dark" placement="top">
              <i class="iconfont icon-guzhangjilu" @click="handleOpenForm(billKey.feedback, row)"></i>
            </el-tooltip>
          </el-badge>
          <el-badge :hidden="wrapperToolTip(row,billKey.qualified)" :value="getToolTipValue(row,billKey.qualified)"
                    class="techne-badge item">
            <el-tooltip class="item" content="不合格审理单" effect="dark" placement="top">
              <i class="iconfont icon-terms" @click="handleOpenForm(billKey.qualified, row)"></i>
            </el-tooltip>
          </el-badge>
          <el-badge :hidden="wrapperToolTip(row,billKey.produceRecord)" :value="getToolTipValue(row,billKey.produceRecord)"
                    class="techne-badge item">
            <el-tooltip class="item" content="生产过程信息记录表" effect="dark" placement="top">
              <i class="iconfont icon-shengchanguochengjilu" @click="handleOpenForm(billKey.produceRecord, row)"></i>
            </el-tooltip>
          </el-badge>
          <el-badge :hidden="wrapperToolTip(row,billKey.processKeyRecord)" :value="getToolTipValue(row,billKey.processKeyRecord)"
                    class="techne-badge item">
            <el-tooltip class="item" content="关键工序质量控制表" effect="dark" placement="top">
              <i class="iconfont icon-guanjiangongxu" @click="handleOpenForm(billKey.processKeyRecord, row)"></i>
            </el-tooltip>
          </el-badge>
          <el-badge :hidden="wrapperToolTip(row,billKey.submitCode)" :value="getToolTipValue(row,billKey.submitCode)"
                    class="techne-badge item" style="margin-right: 5px">
            <el-tooltip class="item" content="提交用户申请单" effect="dark" placement="top">
              <i class="iconfont icon-ic_fluent_checkbox_person_24_filled"
                 @click="handleOpenForm(billKey.submitCode, row)"></i>
            </el-tooltip>
          </el-badge>
        </div>
      </template>
      <template #menu-left>
        <el-button
            v-if="mode === 'worker'"
            type="primary"
            icon="check"
            :loading="checkLoading"
            v-permission="'TechneDeails-SUBMITDATA-SUBMITDATA'"
            @click="submitInspect()"
        >提交</el-button>
        <el-button
            v-if="mode === 'worker'"
            type="primary" plain
            icon="timer"
            :loading="setCompleteTimeLoading"
            v-permission="'TechneDeails-SETCOMPLETETIME-SETCOMPLETETIME'"
            @click="setCompleteTime()"
        >设置完工时间</el-button>
        <el-button
            v-if="mode === 'worker'"
            type="primary" plain
            icon="user-filled"
            :loading="setWorkerNameLoading"
            v-permission="'TechneDeails-BATCHSETWORKER-BATCHSETWORKER-BATCHSETWORKER'"
            @click="batchSetWorkerName()"
        >设置操作员</el-button>
        <el-button
            v-if="mode === 'worker'"
            type="primary" plain
            icon="user-filled"
            :loading="setCheckerNameLoading"
            v-permission="'TechneDeails-BATCHSETCHECKER-BATCHSETCHECKER-BATCHSETCHECKER'"
            @click="batchSetCheckerName()"
        >设置检验员</el-button>
        <el-button
            v-if="mode === 'worker' || mode === 'workerFinish'"
            type="warning" plain
            icon="back"
            :loading="backLoading"
            v-permission="'TechneDeails-REVOKERTOWOKER-REVOKERTOWOKER'"
            @click="revokeToWorker()"
        >撤回工步</el-button>
        <el-button
            v-if="mode === 'checker'"
            type="primary" plain
            icon="circle-check"
            :loading="passLoading"
            v-permission="'TechneDeails-WORKSTEPSPASS-WORKSTEPSPASS'"
            @click="workStepsPass()"
        >工步合格</el-button>
        <el-button
            v-if="mode === 'checker'"
            type="warning" plain
            icon="back"
            :loading="backLoading"
            v-permission="'TechneDeails-WORKSTEPSRETURN-WORKSTEPSRETURN'"
            @click="revokeToWorker()"
        >工步退回</el-button>
        <el-button
            v-if="mode === 'checker' || mode === 'checkerFinish'"
            type="warning" plain
            icon="back"
            :loading="revokeLoading"
            v-permission="'TechneDeails-REVOKETOCHECK-REVOKETOCHECK'"
            @click="revokeToCheck()"
        >撤回检验</el-button>
        <el-button
            type="warning" plain
            icon="milk-tea"
            :loading="onClearCheckerLoading"
            v-permission="'TechneDeails-onClearChecker'"
            @click="onClearChecker()"
        >清除检验员</el-button>
      </template>
    </basic-crud>

    <!--工序的基本信息-->
    <view-techne ref="viewTechneRefs"></view-techne>
    <!--设备工具-->
    <process-definition-equipment ref="processDeRefs" @refresh-parent="handleRefresh"></process-definition-equipment>
    <!--安装记录-->
    <install-record ref="installRecordRef" @refresh-parent="handleRefresh"></install-record>
    <!--取号记录-->
    <ProcessTakeNumber ref="takeNumberRefs" :parentRow="parentRow" @refresh-parent="handleRefresh"></ProcessTakeNumber>
    <!--查杀毒记录-->
    <antivirus-records ref="antivirusRecordsRefs" @refresh-parent="handleRefresh"></antivirus-records>
    <!--问题反馈单-->
    <feedback ref="feedbackRefs" @refresh-parent="handleRefresh"></feedback>
    <!--不合格品审理单-->
    <qualified ref="qualifiedRefs" @refresh-parent="handleRefresh"></qualified>
    <!--生产过程信息记录-->
    <process-record ref="recordRefs" @refresh-parent="handleRefresh"></process-record>
    <!--关键工序质量控制表-->
    <process-qunlity ref="qunlityRefs" @refresh-parent="handleRefresh"></process-qunlity>
    <!--提交用户申请表-->
    <submit-code ref="submitCodeRefs" @refresh-parent="handleRefresh"></submit-code>
    <!--设置完工时间-->
    <basic-dialog v-model="completeTimeDialog.visible" title="设置完工时间" width="600" :submitBtnLoading="setCheckerNameLoading"
                  @cancel="handlerCompleteTimeCancel"
                  @submit="handlerCompleteTimeSubmit">
      <avue-form ref="completeTimeDialogRefs" v-model="completeTimeDialogForm"
                 :option="completeTimeDialogFormOption">
      </avue-form>
    </basic-dialog>
    <!--检验原因-->
    <basic-dialog v-model="revokeReasonDialog.visible" title="工步退回" width="600" :submitBtnLoading="backLoading"
                  @cancel="handlerRevokeReasonCancel"
                  @submit="handlerRevokeReasonSubmit">
      <avue-form ref="revokeReasonDialogRefs" v-model="revokeReasonDialogForm"
                 :option="revokeReasonDialogFormOption">
      </avue-form>
    </basic-dialog>

    <!--人员参照-->
    <BasicCrudUserRefer v-model="userVisible" :selectType="userSelectType" :aptitude="true"
                        @submit="selectUserSubmit"></BasicCrudUserRefer>
  </el-container>
</template>

<script setup>
import ViewTechne from "./ViewTechne.vue";
import processDefinitionEquipment from "./processDefinitionEquipment.vue";
import InstallRecord from "@/views/execute/processFeedback/installRecord.vue";
import ProcessTakeNumber from "./takeNumber.vue";
import AntivirusRecords from "./AntivirusRecords.vue";
import Feedback from "./feedback.vue";
import Qualified from "@/views/mes/techne/qualified.vue";
import ProcessRecord from "./produceRecord.vue";
import ProcessQunlity from "./processQunlity.vue";
import SubmitCode from "./submitCode.vue";

import { getObject } from "@/apis/mes/specificationTask";
import { computed, nextTick, onMounted, useAttrs, watch, ref } from 'vue'
import "@/assets/mes/iconfont/iconfont.css";
import { useUserStore } from '@/store/user'
import { formatDate } from "@/utils/formatTime";
import { useRoute ,onBeforeRouteUpdate} from 'vue-router'
import { getCurrentInstance } from 'vue';
import { useRouterParamsStore } from '@/store/routerParams.js'
import { verifyNotNull, verifyNull } from "@/utils/validate";

import {
  submitToCheck,setFinishWorkDate,checkQualified,
  checkReturn,
  checkRevoke,
} from "@/apis/Techne/TechneDeails.js";
import { changeUser, clearChecker } from "@/apis/generate/treatDispatching.js";
import {ElMessage} from "element-plus";
import {cloneDeep} from "lodash";

// storeToRefs是保持数据的响应式
const { techne } = storeToRefs(useRouterParamsStore())
const route = useRoute()
const { userInfo } = useUserStore()
const userId = userInfo.id

// 定义 props
const props = defineProps({
  hiddenForm: {
    type: Boolean,
    default: false//是否隐藏规程详情
  },
  hiddenBtn: {
    type: Boolean,
    default: false,
  },
  mustShowMenu: {
    type: Boolean,
    default: true//是否显示操作栏
  },
  autoLoad: {
    type: Boolean,
    default: false,
  }
})
const crudAutoLoad=ref(props.autoLoad)
const activeNames = ref(['1'])
const option = {
  calcHeight: 7,
  height:'auto',
  selection: true,
  addBtn: false,
  delBtn: false,
  cancelBtn: true,
  editBtn: false,
  viewBtn:false,
  editBtnText: '更换人员',
  menu:props.mustShowMenu,
  menuWidth: 320,
  searchIndex: 3,
  searchIcon: true,
  //height: Math.max(document.body.clientHeight - 320, 200),
  rowKey: "id",
  rowParentKey: "parentId",
  isTableTree: true,
  defaultExpandAll: true,
  selectable: (row) => {
    let me = false;
    if (mode.value == modeType.worker) {
      //是工人
      if (userId == row.worker || inArray(row.worker, userId)
          || (parentRow.value?.assigner && parentRow.value.assigner == userId)) {
        //已经完成的，也是可以勾选的
        return true;
      }
    } else if (mode.value == modeType.checker) {
      //是检验
      if (userId == row.checker || inArray(row.checker, userId)
          || (parentRow.value?.assigner && parentRow.value.assigner == userId)) {
        if (row.status == status.maked || row.status == status.finish) {
          return true;
        } else {
          return false;
        }
      }
    } else if (mode.value == modeType.workerFinish) {
      //其它
      me = (userId == row.worker || inArray(row.worker, userId)
          || (parentRow.value?.assigner  && parentRow.value.assigner == userId));
      if (me && (row.status == status.maked || row.status == status.finish)) {
        //已完成的任务里，只有撤回工步的功能，这需要加工完成和已完工
        return true;
      }
    } else if (mode.value == modeType.checkerFinish) {
      me = (userId == row.checker || inArray(row.checker, userId)
          || (parentRow.value?.assigner  && parentRow.value.assigner == userId));
      if (me && row.status == status.finish) {
        return true;
      }
    }
    return false;
  },
  column:[
    {
      label: "状态",
      prop: "status",
      width: 110,
      slot: true,
      fixed: "left",
    },{
      label: "工步标识",
      prop: "signText",
      width: 90,
      editDisplay: false,
      fixed: "left"
    },{
      label: "",
      prop: "billCode",
      slot: true,
      width: 60,
      editDisplay: false,
      fixed: "left",
      align:'left'
    },
    {
      label: "工步号",
      prop: "code",
      sort: true,
      slot: true,
      width: 80,
      editDisplay: false,
      fixed: "left",
    },
    {
      label: "工步名称",
      prop: "name",
      sort: true,
      editDisplay: false,
      fixed: "left",
      minWidth: 150,
    },
    {
      label: "固定军检",
      prop: "fixedArmyFlag",
      sort: true,
      slot: true,
      width: 70,
      editDisplay: false,
    },
    {
      label: "操作者",
      prop: "workerName",
      sort: true,
      minWidth: 120,
      formslot: true,
    },
    {
      label: "检验员",
      prop: "checkerName",
      sort: true,
      minWidth: 120,
      formslot: true,
    },
    {
      label: "完工时间",
      prop: "finishWorkDateTime",
      sort: true,
      width: 100,
      editDisplay: false,
      formatter: (row) => {
        if(!row.children || row.children.length == 0 ){
          return formatDate(row.finishWorkDateTime, "yyyy-MM-dd");
        }else {
          return "";
        }
      },
    },{
      label:'退回原因',
      prop: 'revokeReason'
    }
  ]
}

const billKey= {
  code: "code",//工序的基本信息
  installItem: "installItem",//安装记录
  antivirusRecords: "antivirusRecords",//查杀毒记录
  processesKey: "processesKey",//关键工序三定表----现在没有用
  processKeyRecord: "processKeyRecord",//关键工序质量控制表
  feedback: "feedback", //问题反馈
  qualified: "qualified",//不合格品审理单
  takeNumber: "takeNumber",//取号记录
  produceRecord: "produceRecord",//生产过程信息记录
  submitCode: "submitCode",//提交用户申请单,
  processDeCode: "processDeCode",// 设备列表左侧工艺设备列表
}
const billCode= {
  code: "viewTechneRefs",//工序的基本信息
  installItem: "installRecordRef",//安装记录
  antivirusRecords: "antivirusRecordsRefs",//查杀毒记录
  processesKey: "processesKeyRefs",//关键工序三定表
  feedback: "feedbackRefs", //问题反馈
  qualified: "qualifiedRefs",//不合格品审理单
  takeNumber: "takeNumberRefs",//取号记录
  produceRecord: "recordRefs",//生产过程信息记录
  processKeyRecord: "qunlityRefs",//关键工序质量控制表
  submitCode: "submitCodeRefs",//提交用户申请表
  processDeCode: "processDeRefs" //设备工具
}
const modeType = {
  worker: "worker",
  checker: "checker",
  workerFinish: 'workFinish',
  checkerFinish: 'checkerFinish'
}
const status= {
  //与后台的ProcessTaskStatus对应
  maked: "ExecuteFinish",
  finish: "Finish",
  suspend: "Suspended",
  started: "Started",
  allotted: "allotted",
  making: "Executing"
}
//面板折叠展开
const collapseChange=() =>{
  nextTick(() => {
    //let height = this.$refs.collapse.$el.clientHeight;
    //this.stateTable.options.height = document.body.clientHeight - height - 100;
    //this.$refs.crud.doLayout();
  });
}
//规程信息对象
const parentRow=ref({})
//规程主键
const specificationTaskId=ref("")
const mode=ref("processFeedback")
const formColumn=ref(4);
//排序参数
const orderParams=ref({
  orderList: [{ orderBy: "createTime", orderMethod: "desc" }]
})
//列表规程信息参数
const listParams=ref({})

//重新加载列表数据
const loadOnlyBySpecTask=(row, modeV) =>{
  parentRow.value = row;
  specificationTaskId.value= row?.id;
  mode.value = modeV;
  listParams.value.specificationTaskId = specificationTaskId.value
}

//加载列表数据
const initParentRow=()=>{
  if (document.body.clientWidth <= 1900) {
    formColumn.value = 3;
  }
  if (document.body.clientWidth <= 1280) {
    formColumn.value = 2;
  }
  if (document.body.clientWidth > 2560) {
    formColumn.value = 6;
  }

  if (route.query?.fromUndo || (route.query?.type && route.query?.type=='process')) {
    mode.value = route.query.mode;
    specificationTaskId.value = route.query.specTaskId;
    //需要去后台查询一次
    getObject(specificationTaskId.value).then((res) => {
      if (res.success && res.data) {
        parentRow.value = res.data[0];
        crudAutoLoad.value=true
        listParams.value.specificationTaskId = specificationTaskId.value
      } else {
        ElMessage.error(res.msg || '没有找到规程的信息')
      }
    }).catch((error) => {
      ElMessage.error('获取规程任务出错了')
    });
  } else {
    if (techne && techne.value) {
      crudAutoLoad.value=true
      loadOnlyBySpecTask(techne.value.row,techne.value.mode);
    }
  }
}
initParentRow()

const  inArray=(ar, str) => {
  if (!ar || ar == null || !str || str == null) {
    return false;
  }
  if (!Array.isArray(ar)) {
    ar = ar.split(",");
  }
  for (let i = 0; i < ar.length; i++) {
    if (ar[i] == str) {
      return true;
    }
  }
  return false;
}
const  isStep=(row)=> {
  return (!row.children || row.children.length == 0);
}

const crudRef = ref(null)

const wrapperToolTip=(row, key)=> {
  if (!row || !row.billInfo || row.billInfo.length == 0) {
    return true;
  }
  //有且数字大于0，才是false
  var record = row.billInfo.find(val => {
    return key === val.billCode;
  });
  if (record instanceof Array) {
    record = record[0];
  }
  if (record && record.inputCount && parseInt(record.inputCount) > 0) {
    return false;
  }
  return true;
}
const getToolTipValue=(row, key)=> {
  if (!row || !row.billInfo || row.billInfo.length == 0) {
    return "";
  }
  //有且数字大于0，才是false
  var record = row.billInfo.find(val => {
    return key === val.billCode;
  });
  if (record instanceof Array) {
    record = record[0];
  }
  if (record && record.inputCount) {
    return record.inputCount;
  }
  return "";
}

const ins = getCurrentInstance()
// 弹窗
const handleOpenForm=(type, row)=> {
  //weidy@2024-05-21
  // 重新梳理下此处的逻辑，在操作列和数据展示列上面，使用相同的方式
  // 首先分工人模式，还是 检验员模式
  // 工人进入页面模式：
  //        1. 数据状态不是加工完成/已完工，则需要添加和修改等操作
  //             1.1 记录取号，查杀毒记录，问题反馈单，不合格审理单，生产过程信息记录表，关键工序质量控制表，这些没有值的时候，直接显示添加页面
  //             1.2 单据有值的时候，显示列表，上面有继续新增的功能，修改和删除的功能，文件上传的功能，下载文件直接在列上操作
  //        2. 数据是加工完成/已完工，则单据全部显示列表，没有新增，修改，删除，上传的功能

  // 检验员进入页面模式：
  //        1. 数据状态不是已完工，则需要添加和修改等操作
  //             1.1 问题反馈单，不合格审理单 这些没有值的时候，直接显示添加页面
  //             1.2 其余的单据，显示列表，文件不能上传，只能下载
  //        2. 数据是已完工，则单据全部显示列表，没有新增，修改，删除，上传的功能

  if (modeType.worker == mode.value || modeType.workerFinish == mode.value) {
    //工人模式
    //1 数据状态不是加工完成/已完工，则需要添加和修改等操作
    let onlyShow = false;
    if (row.status == 'ExecuteFinish' || row.status == 'Finish') {
      //1.2的情况，只能看列表了
      onlyShow = true;
    }
    if (row.status == 'Suspended' && billKey.feedback != type && billKey.qualified != type) {
      //不是问题和不合格的时候，是停工的时候就都只能看了
      onlyShow = true;
    }
    if (billKey.installItem == type && modeType.worker == mode.value) {
      onlyShow = false;
    }
    if (billKey.installItem == type && modeType.worker != mode.value) {
      onlyShow = true;
    }
    if (billKey.submitCode == type) {
      onlyShow = true;
    }
    var refName = billCode[type];
    if (props.hiddenBtn) {
      onlyShow = true;
    }
    ins.refs[refName].openDialog(row, onlyShow);
  } else {
    // 检验模式
    let onlyShows = false;
    if (row.status == 'Finish') {
      //1.2的情况，只能看列表了
      onlyShows = true;
    } else {
      if (billKey.submitCode == type) {
        onlyShows = false;
      } else {
        onlyShows = true;
      }
    }
    var refNames = billCode[type];
    if (props.hiddenBtn) {
      onlyShows = true;
    }
    ins.refs[refNames].openDialog(row, onlyShows);
  }
}

// 提交检验
const checkLoading = ref(false);
const submitInspect=()=> {
  if (crudRef.value.selectData.length == 0) {
    return ElMessage.error("请先选择要提交检验的工步任务！");
  }
  let processData = crudRef.value.selectData.filter((item) =>
      verifyNotNull(item.parentId)
  );
  //判断任务的状态。为【下达中】与【已下达】不能提交。
  let notStatusDatas = processData.filter((item) =>
      item.status === "allotting" || item.status === "allotted"
  );
  let submitCode = "";
  for (let notData of notStatusDatas) {
    submitCode = submitCode + notData.code + ",";
  }
  if (verifyNotNull(submitCode)) {
    return ElMessage.error("工步号：" + submitCode + "尚未填写产品编号，未开工产品不能进行任务处理！");
  }
  //已提交的状态
  let hasStatusDatas = processData.filter((item) =>
      item.status === "ExecuteFinish" || item.status === "Finish" || item.status === "Suspended"
  );
  for (let hasStatusData of hasStatusDatas) {
    submitCode = submitCode + hasStatusData.code + ",";
  }
  if (verifyNotNull(submitCode)) {
    return ElMessage.error("工步号：" + submitCode + "已提交不允许重复提交！");
  }
  let notSetData = processData.filter((item) =>
      item.status === "ExecuteFinish" || item.status === "Finish"
  );
  if (verifyNotNull(notSetData)) {
    return ElMessage.error("任务已完成，不允许执行当前操作！");
  }
  var _nullData = processData.find((item) => verifyNull(item.worker));
  if (_nullData) {
    return ElMessage.error(_nullData.name + "未填写操作者，请先填写操作者后在提交！");
  }
  //modify 2025-02-28 dangsn 暂时取消加工完成时间的校验。如果未设置加工时间，默认未当前时间。
  /*_nullData = processData.find((item) => verifyNull(item.finishWorkDateTime));
  if (_nullData) {
    this.$message.error(
        _nullData.name + "，这个任务未设置加工完成时间，不能提交！"
    );
    return false;
  }*/
  let idArr = processData.map((item) => {
    return item.id;
  });
  if (idArr == null || idArr == '') {
    return ElMessage.error("选择的任务下面，没有工步的任务，无法执行");
  }
  const params = {};
  params.ids = idArr;
  submitToCheck(params, checkLoading).then((res) => {
    ElMessage.success("提交检验成功！");
    handleRefresh();
  })
}

// 设置完工时间参数
const completeTimeDialog = ref({
  visible: false
});
const completeTimeDialogForm = ref({});
const completeTimeDialogRefs = ref(null);
const completeTimeDialogFormOption = ref({
  menuBtn: false,
  submitBtn: false,
  emptyBtn: false,
  labelWidth: 100,
  column: [
    {
      label: "完工时间",
      prop: "date",
      type: "date",
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      span: 24,
      rules: [
        {
          required: true,
          message: "请选择完工时间",
          trigger: "blur",
        },
      ]
    },
  ]
})
// 设置完工时间按钮事件
const setCompleteTimeLoading = ref(false);
const setCompleteTime=()=>{
  if (crudRef.value.selectData.length == 0) {
    return ElMessage.error("请先选择工步任务！");
  }
  let processData = crudRef.value.selectData.filter((item) =>
      verifyNotNull(item.parentId)
  )
  let notStartedData = processData.filter((item) =>
      item.status === "allotted"
  )
  if (verifyNotNull(notStartedData)) {
    return ElMessage.error("尚未填写产品编号，未开工产品不能进行任务处理！");
  }
  let notSetData = processData.filter((item) =>
      item.status === "ExecuteFinish" || item.status === "Finish"
  );
  if (verifyNotNull(notSetData)) {
    return ElMessage.error("任务已完成，不允许执行当前操作！");
  }
  let idArr = processData.map((item) => {
    return item.id;
  });
  completeTimeDialogForm.value.ids=idArr;
  completeTimeDialog.value.visible=true;
}
// 设置完工时间取消
const handlerCompleteTimeCancel = () => {
  completeTimeDialog.value.visible = false;
  completeTimeDialogRefs.value?.resetFields();
  completeTimeDialogForm.value = {};
}
// 设置完工时间保存
const handlerCompleteTimeSubmit = () => {
    const params = {};
    params.ids = completeTimeDialogForm.value.ids;
    params.finishWorkDateTime = completeTimeDialogForm.value.date;
    if(params.finishWorkDateTime == null || params.finishWorkDateTime == ''){
      return ElMessage.error("请先选择完工时间");
    }
    setFinishWorkDate(params,setCompleteTimeLoading).then((res) => {
      ElMessage.success("设置完工时间成功！");
      handlerCompleteTimeCancel();
      handleRefresh()
    });
};

//人员参照弹窗
const userVisible = ref(false);
const userSelectType=ref('multiple')
const selectUserType=ref('')
// 批量设置操作员
const setWorkerNameLoading = ref(false);
const batchSetWorkerName=() =>{
  if (crudRef.value.selectData.length == 0) {
    return ElMessage.error("请选择至少一条需要设置人员的数据！");
  }
  let notStartedData = crudRef.value.selectData.filter(
      (item) => item.status === status.allotted
  );
  if (verifyNotNull(notStartedData)) {
    return ElMessage.error("尚未填写产品编号，未开工产品不能进行任务处理！");
  }
  let notSetData = crudRef.value.selectData.filter(
      (item) => item.status === "ExecuteFinish" || item.status === "Finish"
  );
  if (verifyNotNull(notSetData)) {
    return ElMessage.error("任务已完成，不允许执行当前操作！");
  }
  userVisible.value=true;
  selectUserType.value = "workBatch";
  userSelectType.value='multiple';
}

// 批量设置检验员
const setCheckerNameLoading = ref(false);
const batchSetCheckerName=()=>{
  if (crudRef.value.selectData.length == 0) {
    return ElMessage.error("请选择至少一条需要设置人员的数据！");
  }
  let notStartedData = crudRef.value.selectData.filter(
      (item) => item.status === status.allotted
  );
  if (verifyNotNull(notStartedData)) {
    return ElMessage.error("尚未填写产品编号，未开工产品不能进行任务处理！");
  }
  let notSetData = crudRef.value.selectData.filter(
      (item) => item.status === "ExecuteFinish" || item.status === "Finish"
  );
  if (verifyNotNull(notSetData)) {
    return ElMessage.error("任务已完成，不允许执行当前操作！");
  }
  userVisible.value=true;
  selectUserType.value = "checker";
  userSelectType.value='radio';
}

//人员选择回调
const selectUserSubmit=(selections) => {
  //过滤出工步任务
  let processData = crudRef.value.selectData.filter((item) => verifyNotNull(item.parentId));
  let _ids = processData.map((item) => {
    return item.id;
  });
  let params = {ids: _ids};
  if (selectUserType.value == 'workBatch') {
    params.worker = selections.map(val => val.id).join(",");
    params.workerCode = selections.map(val => val.code).join(",");
    params.workerName = selections.map(val => val.name).join(",");
    params.changeUserType = "0";
  } else {
    //检验员
    params.checker = selections.id;
    params.checkerCode = selections.code;
    params.checkerName = selections.name;
    params.changeUserType = "1";
  }
  changeUser(params,selectUserType.value == 'workBatch'?setWorkerNameLoading:setCheckerNameLoading).then((res) => {
    ElMessage.success("修改成功！");
    userVisible.value=false;
    selectUserType.value = "";
    handleRefresh();
  })
}

// 撤回工步
const backLoading = ref(false);
const revokeToWorker=()=> {
  if (crudRef.value.selectData.length == 0) {
    return ElMessage.error("请先选择要退回的工步任务！");
  }
  //过滤出工步任务
  let processData = crudRef.value.selectData.filter((item) =>
      verifyNotNull(item.parentId)
  )
  if (processData.length == 0) {
    return ElMessage.error("选择的数据不是可退回的工步任务！");
  }
  //校验选择的任务中，是否属于当前人
  let _flag = verifyChecker(processData);
  if (!_flag) {
    return ElMessage.error("没有可退回的工步！");
  }
  //判断任务的状态。只有【开工】后【加工完成】状态的任务才能撤回。
  let notStartedData = processData.filter(
      (item) => item.status === status.allotted
  );
  if (verifyNotNull(notStartedData)) {
    return ElMessage.error("尚未填写产品编号，未开工产品不能进行任务处理！");
  }
  let notSetData = processData.filter(
      (item) => (item.status !== status.maked && !(item.status == status.finish && !verifyNotNull(item.checker)))
  );
  if (verifyNotNull(notSetData)) {
    return ElMessage.error("任务正在执行或已完成，不允许执行当前操作！");
  }

  let idArr = processData.map((item) => {
    return item.id;
  });
  const params = {};
  params.id = idArr.join(",");
  //以区别从过程反馈还是检验哪里，退回工步的
  if (mode.value === modeType.worker || mode.value === modeType.workerFinish) {
    params.returnType = "work";
    //是工人的直接执行
    checkReturn(params, backLoading)
        .then((res) => {
          ElMessage.success("工步退回成功！");
          handleRefresh();
        })
  } else {
    //是检验的，要填写检验的原因
    revokeReasonDialogForm.value.ids=params.id;
    revokeReasonDialog.value.visible=true;
  }
}

// 检验原因参数
const revokeReasonDialog = ref({
  visible: false
});
const revokeReasonDialogForm = ref({});
const revokeReasonDialogRefs = ref(null);
const revokeReasonDialogFormOption = ref({
  menuBtn: false,
  submitBtn: false,
  emptyBtn: false,
  labelWidth: 100,
  column: [
    {
      label: "退回原因",
      prop: "revokeReason",
      type: "textarea",
      span: 24,
      rules: [
        {
          required:true,
          message:'退回原因不能为空',
          trigger:'blur'
        },
      ]
    },
  ]
})
// 检验原因取消
const handlerRevokeReasonCancel = () => {
  revokeReasonDialog.value.visible = false;
  revokeReasonDialogRefs.value?.resetFields();
  revokeReasonDialogForm.value = {};
}
// 检验原因保存
const handlerRevokeReasonSubmit = () => {
  const params = {};
  params.id = revokeReasonDialogForm.value.ids;
  params.revokeReason = revokeReasonDialogForm.value.revokeReason;
  params.returnType = "check";
  checkReturn(params,backLoading).then((res) => {
    ElMessage.success("工步退回成功！");
    handlerRevokeReasonCancel();
    handleRefresh()
  });
};

// 工步合格
const passLoading = ref(false);
const workStepsPass=()=> {
  if (crudRef.value.selectData.length <= 0) {
    return ElMessage.error("请先选择要提交检验的工步任务！");
  }
  //过滤出工步任务
  let processData = crudRef.value.selectData.filter((item) =>
      verifyNotNull(item.parentId)
  );
  if (processData.length == 0) {
    return ElMessage.error("选择的数据不是可操作的工步任务！");
  }
  //校验选择的任务中，是否属于当前人
  let _flag = verifyChecker(processData);
  if (!_flag) {
    return ElMessage.error("没有可操作的工步！");
  }
  //判断任务的状态。只有【加工完成】状态的任务才能提交。
  let notSetData = processData.filter(
      (item) => item.status === "Finish"
  );
  if (verifyNotNull(notSetData)) {
    return ElMessage.error("任务已完成，不允许执行当前操作！");
  }

  let idArr = processData.map((item) => {
    return item.id;
  });
  const params = {
    id: idArr.join(",")
  };
  checkQualified(params, passLoading).then((res) => {
    ElMessage.success("提交检验成功！");
    handleRefresh();
  });
}

//撤回检验
const revokeLoading = ref(false);
const revokeToCheck=()=> {
  if (crudRef.value.selectData.length <= 0) {
    return ElMessage.error("请选择至少一条需要操作的数据！");
  }
  //过滤出工步任务
  let processData = crudRef.value.selectData.filter((item) =>
      verifyNotNull(item.parentId)
  );
  if (processData.length == 0) {
    return ElMessage.error("选择的数据不是可操作的工步任务！");
  }
  //校验选择的任务中，是否属于当前人
  let _flag = verifyChecker(processData);
  if (!_flag) {
    return ElMessage.error("没有可操作的工步！");
  }
  //判断任务的状态。只有【已完成】状态的任务才能提交。
  let notSetData = processData.filter((item) => item.status !== "Finish");
  if (verifyNotNull(notSetData)) {
    return ElMessage.error("任务未完成，不允许执行当前操作！");
  }

  let idArr = processData.map((item) => {
    return item.id;
  });
  const params = {};
  params.id = idArr.join(",");
  checkRevoke(params,revokeLoading).then((res) => {
    if (res.success) {
      ElMessage.success("撤回成功！");
      handleRefresh();
    }
  });
}

//清除检验员
const onClearCheckerLoading = ref(false);
const onClearChecker=() => {
  if (crudRef.value.selectData.length == 0) {
    return ElMessage.error("请选择至少一条需要设置人员的数据！");
  }
  let finishStatus = crudRef.value.selectData.filter(
      (item) => item.status === "finish"
  );
  if (verifyNotNull(finishStatus)) {
    return ElMessage.error("任务已经完成了的，不能取消检验员");
  }
  let ids = crudRef.value.selectData.map(value => value.id);
  ElMessageBox.confirm('是否清除检验员，清除后这个任务将不会执行检验', '需您确认').then(() => {
    clearChecker(ids, onClearCheckerLoading).then(res => {
      ElMessage.success("移除成功");
      handleRefresh();
    })
  });
}

const verifyChecker=(selectRows)=> {
  let notSetData = false;
  if (mode.value === modeType.checker) {
    //检验员
    notSetData = selectRows.filter((item) => item.checker !== userId);
    if (verifyNotNull(notSetData)) {
      return ElMessage.error("选择的任务中，存在不属于当前用户的任务，请重新选择！");
    }
  }
  if (mode.value === modeType.worker || mode.value == modeType.workerFinish) {
    //是工人的。
    notSetData = selectRows.filter((item) =>
        item.worker !== userId
        && !inArray(item.worker.split(","), userId)
        && !(parentRow && parentRow.assigner && parentRow.assigner == userId));
    if (verifyNotNull(notSetData)) {
      return ElMessage.error("选择的任务中，存在不属于当前用户的任务，请重新选择！");
    }
  }
  return true;
}

const handleRefresh=()=>{
  crudRef.value.getList();
}
defineExpose({
  initParentRow,
  loadOnlyBySpecTask
})

watch(
    route,
    (newV) => {
      if(newV.path=="/techne"){
        initParentRow()
      }
    },
    {
      immediate: true,
      deep: true,
    }
)
</script>

<style lang="scss" scoped>
::v-deep {
  .el-collapse-item__header{
    height: 35px;
    line-height: 35px;
  }
  .el-collapse-item__content{
    padding-bottom: 5px;
  }
  .el-collapse-item__content .iconfont{
    margin-left: 8px;
    font-size: 14px;
  }
  .el-descriptions__cell{
    padding-right: 10px;
  }
}
</style>

<style lang="scss">
.techne-badge {
  margin-right: 16px;

  .el-badge__content {
    height: 14px;
    line-height: 12px;
    transform: translateY(-10%) translateX(125%);
    padding: 0 4px;
    border-radius: 6px;
  }

  .iconfont {
    font-size: 18px;
  }
}

.icon-margin {
  margin-right: 5px;
}
</style>